package fd.sudoku.main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import fd.sudoku.data.SudokuMap;
import fd.sudoku.logical.Processor;
import fd.sudoku.utility.SudokuCheck;

public class SudokuMain {

	private SudokuMap readMaps(InputStream in)
	{
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		String line = null;
		List<String> theNumbers = new ArrayList<String>();
		try {
			line = reader.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		while(line != null && !line.trim().startsWith("e"))
		{
			String[] numbers = line.split(",");
			for(String number : numbers)
			{
				theNumbers.add(number.trim());
			}
			try {
				line = reader.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		SudokuMap sudokuMap = new SudokuMap(theNumbers);
		return sudokuMap;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{

		SudokuMain main = new SudokuMain();
		InputStream in = null;
		if(args!= null && args.length >0)
		{
		    File file = new File(args[0]);
		    try 
		    {
                in = new FileInputStream(file);
            } 
		    catch (FileNotFoundException e)
		    {
		        System.out.println(file.getAbsolutePath());
                e.printStackTrace();
            }
		}
		else
		{
		    System.out.println("Input the sudoku Map, end with \'e\' !");
		    in = System.in;
		}
		SudokuMap map = main.readMaps(in);
		SudokuMap theSudokuMap = Processor.handler(map);
		System.out.println(map.toString());
		if(SudokuCheck.checkMap(map))
		{
			System.out.println("It is the valide Sudoku Map!");
		}
		else
		{
			System.out.println("It is the invalide Sudoku Map!");
			System.out.println("Process it now?");
			try {
	            System.in.read();
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
			System.out.println("The Valide one is: ");
			System.out.println(theSudokuMap.toString());
		}
		
		System.out.println("Input any key to stop it!");
		try {
            System.in.read();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
	}

}
